#include "sqllite.h"

/*!
\class SqlLite
Class for managing the connection to a SQLite database
*/


/*!
  \fn SqlLite
  Constructor with no Params
*/
SqlLite::SqlLite()
{
    this->lastErrorMessage = "";
}


/*!
  \fn connect
  Function to connect to the Database
  \param path: Path the the databaseFile
  \returns true if action successfully completed
*/
bool SqlLite::connect(QString path)
{
    //Definition of the Variables
    bool error;

    //Get the database and set the path
    this->db = QSqlDatabase::database("sqlDb", false);
    this->db.setDatabaseName(path);

    //Open the database Connection
    error = this->db.open();

    if (!error)
        this->lastErrorMessage = this->db.lastError().text();

    this->query = new QSqlQuery(this->db);

    return error;
}

/*!
    Function to dissconnect from the Database
*/
void SqlLite::disconnect()
{
    this->query->clear();
    this->db.close();
    delete this->query;
}


/*!
    Function to execute a Update
    \param sqlCommand, QString with the to execute SQL Command
    \returns true if the command is executed successfull
 */
bool SqlLite::executeCommand(QString sqlCommand)
{
    bool error;

    error = this->query->exec(sqlCommand);

    if (!error)
        this->lastErrorMessage = this->query->lastError().text();

    return true;
}

/*!
    Function to check if Problems with the database exists
    \param path: Path the the databaseFile
    \returns true database ok, else false
 */
bool SqlLite::checkDatabase(QString path)
{
    //Definition of the Variables
    bool error;

    //Get the database and set the path
    this->db = QSqlDatabase::database("sqlDb", false);
    this->db.setDatabaseName(path);

    //Open the database Connection
    error = this->db.open();

    if (!error)
        this->lastErrorMessage = this->db.lastError().text();
    else
    {
        this->query = new QSqlQuery(this->db);
        error = this->query->exec("Select aId from athlete;");
        if (!error)
            this->lastErrorMessage = this->query->lastError().text();
    }
    return error;
}



/////////////////////
//Getter Functions//
///////////////////


/*!
  \fn getQuery
  Functions which returns a Pointer to the QSqlQuery
  \returns Pointer to the QSqlQuery
  */
QSqlQuery *SqlLite::getQuery()
{
    return this->query;
}

/*!
  \fn getLastIndex
  Functions which returns the Last Index of the inserted row
  \returns last index
  */
int SqlLite::getLastIndex()
{
    return query->lastInsertId().toInt();
}

/*!
  \fn getLasterErrorMessage
  Functions which returns the last Error Message
  \returns Last error Message
  */
QString SqlLite::getLasterErrorMessage()
{
    return this->lastErrorMessage;
}





